//
//  BCIPAddressHelper.m
//  BanChinaFramework
//
//  Created by Ann on 2024/3/11.
//

#import "BCIPAddressHelper.h"

@implementation BCIPAddressHelper

+ (void)getUserIPAddressWithCompletion:(IPCompletionHandler)completion {
    
    NSURL *url = [NSURL URLWithString:@"https://api.ipify.org?format=json"]; // 使用ipify提供的服务获取IP地址
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"获取ip地址错误: %@", error.localizedDescription);
            completion(nil);
        } else {
            NSError *jsonError;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
            if (jsonError) {
                NSLog(@"错误的格式: %@", jsonError.localizedDescription);
                if (completion) {
                    completion(nil);
                }
            } else {
                NSString *ipAddress = json[@"ip"];
                // 验证IP地址
                if (completion) {
                    completion(ipAddress);
                }
            }
        }
    }];
    
    [task resume];
}

+ (void)interceptChinaUserHandler:(void (^_Nullable)(BCIPAddressChinaUser user))completed {
    [self getUserIPAddressWithCompletion:^(NSString * _Nullable ipAddress) {
        if (ipAddress) {
            [self fetchCountryForIPAddress:ipAddress handler:completed];
        } else {
            if (completed) {
                completed(BCIPAddressChinaUserUnknown);
            }
        }
    }];
}

+ (void)fetchCountryForIPAddress:(NSString *)ipAddress handler:(void (^_Nullable)(BCIPAddressChinaUser user))completed
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://geolocation-db.com/json/%@&position=true", ipAddress]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            if (completed) {
                completed(BCIPAddressChinaUserUnknown);
            }
            return;
        }
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSString *countryName = json[@"country_name"];//China
        NSString *countryCode = json[@"country_code"];//CN
        NSLog(@"%@,%@",countryName,countryCode);
        if ([countryName isEqualToString:@"China"] && [countryCode isEqual:@"CN"]) {
            if (completed) {
                if (completed) {
                    completed(BCIPAddressChinaUserYES);
                }
            }
        } else {
            if (completed) {
                completed(BCIPAddressChinaUserNO);
            }
        }
    }];
    
    [task resume];
}

@end
